﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

#region SLICReferences

using SLIC.Models.Admin;
using SLIC.Models.Enums;

#endregion SLICReferences

#region ThirdPartyReferences
using log4net;
using MvcContrib.Pagination;
#endregion ThirdPartyReferences

namespace SLIC.Controllers
{
    public class AdminController : BaseController
    {
        protected static readonly ILog log = LogManager.GetLogger("root");
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            return View();
        }

        ///Generate report with log details
        ///<param name="page">Page Name</param> 
        ///<returns>
        ///List of logs  
        ///</returns>       
        ///<exception cref="">
        ///error in parameters
        ///error in data 
        ///error in log file 
        /// </exception>
        /// <remarks></remarks>
        public ActionResult ViewReports(int? page)
        {
            FileStream fs = null;
            List<SLICLogEntry> report = new List<SLICLogEntry>();

            try
            {
                fs = new FileStream(Server.MapPath("~/Logs/") + "log.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                StreamReader r2 = new StreamReader(fs);
                //string[] lines = System.IO.File.ReadAllLines(Server.MapPath("~/Logs/")+"log.txt");
                string t = "";
                while ((t = r2.ReadLine()) != null)
                {
                    SLICLogEntry log = new SLICLogEntry();

                    try
                    {
                        string[] array = t.Split('#');

                        log.Type = array[0];
                        log.Date = array[1];
                        int index = array[2].IndexOf("[Params=(", 0);

                        string actionData = array[2];

                        if (index != -1)
                        {
                            try
                            {                          //Have Params
                                actionData = array[2].Substring(0, index);
                                string paramString = array[2].Substring(index);
                                //ERROR!!!
                                log.Params = paramString.Substring(paramString.IndexOf("(") + 1, paramString.IndexOf(")") - paramString.IndexOf("(")-1);
                            }
                            catch (Exception e)
                            {
                                log.Params = "Error in extracting parameters.";
                            }
                        }
                        string[] actionDataArray = actionData.Split(',');
                        if (actionData.Length > 2)
                        {
                            log.Controller = actionDataArray[1];
                        }
                        if (actionData.Length > 3)
                        {
                            log.Action = actionDataArray[2];
                        } if (actionData.Length > 4)
                        {
                            log.ActionBy = actionDataArray[3];
                        }
                    }
                    catch (Exception)
                    {
                        log.Params = "Error in processing data.";
                    }
                    report.Add(log);
                }
            }
            catch (Exception)
            {
                //  log.Info(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",View Reports," + User.Identity.Name);
                ModelState.AddModelError("err", new GenException(400, "Error while reading the file"));
                return RedirectToAction("Index", "Default");
            }
            finally
            {
                fs.Dispose();
            }
            // log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("log4net.xml")));
            //log.Info(LogPoint.Success.ToString()  +"," + this.ControllerContext.Controller.ToString() + ",View Reports," + User.Identity.Name);
            return GetFormatView("Admin/Report.aspx", report.AsQueryable().AsPagination(page ?? 1, 10));
        }
    }
}
